package formatter;

import java.util.Map;

import logging.LoggerConstants;
import logging.Record;

public class AbstractFormatter{

	/*
	 * return the formatter message
	 */
//	public abstract String applyFormat(Record dataRecord) throws InvalidFormatException;

	protected Map<String, MessagePattern> mapPattern;
	protected String typeFormat;
	protected IFormatter chainFormatter;
	
	public void setChainFormatter(IFormatter chain){
		this.chainFormatter = chain;
	}

	protected void setMap(Record dataRecord, String[] patterns) {
		// String[] patterns = this.getPatterns();
		this.mapPattern.put("%n", new ConstantPattern(LoggerConstants.separatorDefault));
		this.mapPattern.put("%p", new LevelPattern(dataRecord.getLevel()));
		this.mapPattern.put("%t", new ThreadPattern());
		this.mapPattern.put("%m", new MessageUserPattern(dataRecord.getMessage()));
		this.mapPattern.put("%%", new ConstantPattern(LoggerConstants.porcent));
		this.mapPattern.put("%g", new LoggerNamePattern(dataRecord.getLoggerName()));
		this.mapPattern.put("%L", new LineNumberPattern());
		this.mapPattern.put("%F", new FileNamePattern());
		this.mapPattern.put("%M", new MethodPattern());
		for (String p : patterns) {
			if (p.contains("%d")) {
				this.mapPattern.put("%d", new DateFormatPattern(this.getFormatDate(p)));
				break;
			}
		}
	}

	protected String getFormatDate(String pattern) {
		String output = "";
		int firstPos = pattern.indexOf("{");
		int lastPos = pattern.indexOf("}");
		if ((firstPos >= 0) && (lastPos >= 0)) {
			output = pattern.substring(firstPos + 1, lastPos);
		}
		return output;
	}

}
